﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Sherwood.Imaging
{
    public class GetImageHandler : IHttpHandler
    {
        private static readonly ITemplateContainer Container;

        static GetImageHandler()
        {
            Container = DependencyInjection.Resolve<ITemplateContainer>();
        }

        public void ProcessRequest(HttpContext context)
        {
            var virtualPath = context.Request.Url.PathAndQuery.Substring(context.Request.FilePath.Length);
            var strings = virtualPath.Substring(1).Split('/');
            if(!virtualPath.StartsWith("/") || strings.Length == 0)
            {
                context.Response.StatusCode = 404;
                return;
            }
            var templateName = strings[0];

            var template = Container.Resolve(templateName);

            context.Response.ContentType = template.ContentType;
            template.SaveToStream(context.Response.OutputStream);
        }

        public bool IsReusable { get { return true; } }
    }
}
